package com.byxy.action;

import com.byxy.entity.Product;
import com.byxy.entity.User;
import com.byxy.service.DetailService;
import com.byxy.service.SorderService;
import com.byxy.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@Scope("prototype")
public class DetailAction extends ActionSupport {
	private Integer id;
	private Product product;
	@Autowired
	private DetailService detailService;
	@Autowired
	private SorderService sorderService;
	@Autowired
	private UserService userService;

	public String detail() {
		System.out.println("id: " + id);
		product = detailService.getProductById(id);
		ServletActionContext.getRequest().getSession().setAttribute("product", product);
		return SUCCESS;
	}

	public String addSorder() {
		product = detailService.getProductById(product.getId());
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("u");
		if (user == null) {
			List<Product> cart = (List<Product>) ServletActionContext.getRequest().getSession().getAttribute("cart");
			if (cart == null) {
				cart = new ArrayList<>();
			}
			cart.add(product);
			BigDecimal price = new BigDecimal(0);
			for (Product product : cart) {
				price = price.add(product.getPrice());
			}
			ServletActionContext.getRequest().getSession().setAttribute("price", price);
			ServletActionContext.getRequest().getSession().setAttribute("num", cart.size());
			ServletActionContext.getRequest().getSession().setAttribute("cart", cart);
		} else {
			user = userService.get(user.getId());
			detailService.saveSorder(product, user);
			ServletActionContext.getRequest().getSession().setAttribute("num", sorderService.getSorderNum(user));
			ServletActionContext.getRequest().getSession().setAttribute("price", sorderService.getSorderPrice(user));
		}
		return SUCCESS;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}
}
